<template>
    <div :class="{ 'dark-mode': isDark }" class="app-list-container">
        <header><b>云浩APP后台</b></header>
        <!-- 应用列表表格 -->
        <el-table :data="paginatedApps" border style="width: 100%; margin-bottom: 72px" v-loading="loading" row-key="id">
            <el-table-column prop="name" label="应用名称" width="180" align="center" />
            <el-table-column prop="category" label="分类" width="120" align="center">
                <template #default="{ row }">
                    {{ formatCategory(row.category) }}
                </template>
            </el-table-column>
            <el-table-column prop="version" label="版本号" width="120" align="center" />
            <el-table-column prop="description" label="描述" show-overflow-tooltip align="center" />
            <el-table-column label="链接" width="220" fixed="right" align="center">
                <template #default="{ row }">
                    <el-button type="primary" @click="copyLink(row)">复制APP链接</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right" align="center">
                <template #default="{ row }">
                    <el-popconfirm title="确认删除该应用？" confirm-button-text="确认" cancel-button-text="取消" icon-color="#F56C6C"
                        @confirm="handleDelete(row.id)">
                        <template #reference>
                            <el-button type="danger" size="small" :icon="Delete" circle class="delete-btn" />
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 固定底部分页 -->
        <div class="fixed-pagination">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper" :total="total" background @size-change="handleSizeChange"
                @current-change="handlePageChange" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive, watch } from 'vue';
import { Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { commonMessage } from "@/utils/index.js";
import { $_getapp, $_deleteapp } from "@/api/yh";

// 暗黑模式状态
const isDark = ref(localStorage.getItem('darkMode') === 'true' || false);

// 应用数据
const apps = reactive([]);

// 获取应用数据
const getApps = () => {
    $_getapp().then(res => {
        Object.assign(apps, res.result);
        // 数据获取后直接排序
        apps.sort((a, b) => new Date(b.updateDate) - new Date(a.updateDate));
    });
};

getApps();

// 排序应用
const sortedApps = computed(() => {
    return [...apps].sort((a, b) => new Date(b.updateDate) - new Date(a.updateDate));
});

// 分页数据
const paginatedApps = computed(() => {
    const start = (currentPage.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    return sortedApps.value.slice(start, end);
});

// 响应式数据
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = computed(() => apps.length);

// 分类映射
const categories = {
    cashier: '收银系统'
};

// 初始化数据
onMounted(() => {
    fetchData();
});

// 获取数据方法（带分页优化）
const fetchData = async () => {
    try {
        loading.value = true;
        await new Promise(resolve => setTimeout(resolve, 500));

        const totalPages = Math.ceil(apps.length / pageSize.value);
        if (currentPage.value > totalPages) {
            currentPage.value = Math.max(totalPages, 1);
        }
    } finally {
        loading.value = false;
    }
};

// 分页事件处理
const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    // 处理跨页数据边界
    if (currentPage.value > Math.ceil(total.value / newSize)) {
        currentPage.value = 1;
    }
    fetchData();
};

const handlePageChange = () => {
    window.scrollTo({ top: 0, behavior: 'smooth' }); // 滚动到顶部
    fetchData();
};

// 删除处理（带分页优化）
const handleDelete = async (id) => {
    try {
        let res = await $_deleteapp({id});
        if (res.success) {
            // 删除后的分页处理
            if (paginatedApps.value.length === 1 && currentPage.value > 1) {
                currentPage.value--;
            }
            ElMessage.success('删除成功');
            fetchData();
        }


    } catch (error) {
        ElMessage.error('删除失败');
    }
};

// 分类格式化
const formatCategory = (val) => {
    return categories[val] || '未知分类';
};

// 复制链接
const copyLink = (value) => {
    const link = value.link;
    console.log(link, '复制链接处理...');
    // 复制
    navigator.clipboard.writeText(link)
        .then(() => {
            commonMessage('链接已复制到剪贴板');
        })
        .catch(() => {
            commonMessage('复制链接失败', 'error');
        });
};
</script>

<style scoped lang="scss">
header {
    width: 100%;
    text-align: center;
    height: 60px;
    line-height: 60px;
    background: #fff;
    position: fixed;
    top: 0;
    left: 0;
    z-index: 1000;
    font-size: 30px;
    box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
}

.app-list-container {
    position: relative;
    min-height: calc(100vh - 60px);
    padding: 20px;
}

/* 固定底部分页 */
.fixed-pagination {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px 24px;
    background: var(--el-bg-color);
    box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
    z-index: 1000;
    transition: background 0.3s;
    display: flex;
    justify-content: flex-end;
}

/* 删除按钮美化 */
.delete-btn {
    transition: all 0.3s;
    padding: 6px;
}

.delete-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 2px 6px rgba(245, 108, 108, 0.3);
}

/* 暗黑模式适配 */
.dark-mode .fixed-pagination {
    box-shadow: 0 -2px 12px rgba(255, 255, 255, 0.1);
}

.el-table {
    margin-bottom: 72px !important;
    margin-top: 60px !important;
}
</style>